//
//  PopoverAnimator.swift
//  LBWeibo
//
//  Created by 李博 on 15/6/28.
//  Copyright © 2015年 libo. All rights reserved.
//

import UIKit

class PopoverAnimator: NSObject,UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning{
    
    var presentFrame = CGRectZero
    
    /// 是否展现的标记
    var isPresented = false
    
    // 返回负责转场的控制器对象
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        
        let pc = PopoverPresentationController(presentedViewController: presented, presentingViewController: presenting)
        
        pc.presentFrame = presentFrame
        
        return pc
    }
    //返回提供动画的modal对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        return self
    }
    //返回提供 dismissed 动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = false
        return self
    }
    
    //动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        
        return 1.2
    }
    
    ///  转场动画实现函数 － 一旦实现此函数，默认的动画失效，所有的动画由程序员提供
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
       
        //判断是展示还是dismiss
        if isPresented {
            //目标视图
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            //将toView添加到容器视图
            transitionContext.containerView()?.addSubview(toView)
            
            //动画实现
            toView.transform = CGAffineTransformMakeScale(1.0, 0)
            toView.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10.0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
                
                toView.transform = CGAffineTransformIdentity
                
                }, completion: { (_) -> Void in
                    //结束动画
                    transitionContext.completeTransition(true)
            })
            
        }else{
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)
            fromView?.removeFromSuperview()
            //结束动画
            transitionContext.completeTransition(true)
        }
        
    }
    
    
    
    
    

}
